<template>
  <div class="bigbox">
    <div class="topbox">
      <el-form
        :model="form"
        ref="form"
        label-position="left"
        label-width="80px"
        onsubmit="return false"
      >
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="用电企业">
              <FilterSelect2
                v-model="bizOrgNo"
                :optionlist="companyList"
                :valuekey="{ name: 'name', value: 'id' }"
                @changeSelect="companyChange"
              ></FilterSelect2>
            </el-form-item>
          </el-col>
          <el-col :span="19" style="text-align: right">
            <el-form-item>
              <Twobtn @chaxun="chaxun" @chongzhi="chongzhi"></Twobtn>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="bodybox">
      <div class="titlebox">
        <div class="text"></div>
        <TopTile
          @command="command"
          @daochu="daochu"
          @shuaxin="shuaxin"
        ></TopTile>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
        ref="table"
        :size="iissize"
        :header-cell-style="{
          background: '#f5f5f5',
          'text-align': 'center'
        }"
      >
        <template slot="empty">
          <el-empty description="暂无数据"></el-empty>
        </template>
        <el-table-column type="index" align="center" label="序号" width="150">
        </el-table-column>
        <el-table-column prop="companyName" label="用电企业"> </el-table-column>
        <el-table-column prop="className" label="设备名称"> </el-table-column>
        <el-table-column align="center" prop="bh" label="编号">
        </el-table-column>
        <el-table-column align="center" prop="type" label="设备型号">
        </el-table-column>
        <el-table-column prop="factory" label="生产厂家"> </el-table-column>
        <el-table-column align="center" prop="ccrq" label="出厂时间">
        </el-table-column>
        <el-table-column align="center" prop="runDate" label="投运时间">
        </el-table-column>
        <el-table-column prop="maintenance" label="维保周期(天)">
        </el-table-column>
        <el-table-column
          align="center"
          prop="nextMaintenanceDate"
          label="下次维保时间"
        >
        </el-table-column>
        <el-table-column align="center" prop="contact" label="联系人">
        </el-table-column>
        <el-table-column align="center" prop="telephone" label="联系电话">
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <div
              style="color: #29baf7; cursor: pointer"
              @click="updateRecord(scope.row)"
            >
              更新维保记录
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="fenye">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="pageobj._pageNo"
          :page-size.sync="pageobj._pageSize"
          @current-change="getdatalist()"
          :total="10"
        >
        </el-pagination>
      </div>
      <nt-dialog
        title="维保卡信息"
        :visible.sync="dialogVisible"
        v-if="dialogVisible"
        width="500px"
        @diaClose="diaClose"
      >
        <el-form ref="dialogForm" :model="dialogForm" label-width="auto">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="设备编号">
                <el-input v-model="dialogForm.bh" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备名称">
                <el-input v-model="dialogForm.className" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="维保年份">
                <el-date-picker
                  v-model="dialogForm.maintenanceYear"
                  type="year"
                  placeholder="选择年"
                  format="yyyy"
                  value-format="yyyy"
                  style="width: 100%"
                >
                </el-date-picker>
              </el-form-item>
              <el-divider />
            </el-col>
            <el-col :span="24">
              <el-form-item label="维护时间">
                <el-date-picker
                  v-model="dialogForm.maintenanceDate"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="维保情况">
                <el-input v-model="dialogForm.maintenanceSituation"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="附件">
                <el-upload
                  class="upload-demo"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :limit="1"
                  :on-change="onChange"
                  :on-remove="onRemove"
                  :auto-upload="false"
                  :file-list="fileList"
                >
                  <el-button class="upload"
                    ><i class="el-icon-plus"></i
                  ></el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <div style="margin-top: 10px; text-align: center">
            <span slot="footer" class="dialog-footer">
              <el-button @click="diaClose">取 消</el-button>
              <el-button type="primary" @click="submit">确 定</el-button>
            </span>
          </div>
          <div style="margin-bottom: -10px; margin-top: 10px">历史维保记录</div>
          <el-divider />
          <el-table
            :data="tableList2"
            style="width: 100%"
            border
            height="200px"
            ref="table"
            :size="iissize"
            :header-cell-style="{
              background: '#f5f5f5',
              'text-align': 'center'
            }"
          >
            <template slot="empty">
              <el-empty description="暂无数据"></el-empty>
            </template>
            <el-table-column
              align="center"
              type="index"
              label="序号"
              width="50px"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="maintenanceYear"
              label="维保年份"
              width="60px"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="maintenanceDate"
              label="维保时间"
            >
            </el-table-column>
            <el-table-column prop="maintenanceSituation" label="维保情况">
            </el-table-column>
            <el-table-column prop="maintenanceName" label="附件">
              <template slot-scope="scope">
                <span
                  style="color: #50baf7; cursor: pointer"
                  @click="
                    downloadFile(
                      scope.row.maintenanceName,
                      scope.row.maintenanceFile
                    )
                  "
                >
                  {{ scope.row.maintenanceName }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </nt-dialog>
    </div>
  </div>
</template>

<script>
// import { saveAs } from 'file-saver'
import {
  addMaintenanceApi,
  getCompanyListApi,
  getMaintenanceListApi,
  getPageListApi
} from '@/api/energy-consumption/Equipment-energy/Account-management'
import { exportexcel } from '@/utils/excel'
import ntDialog from '@/components/nt-dialog.vue'
import dayjs from 'dayjs'
export default {
  components: { ntDialog },
  name: 'AccountManagement',
  data() {
    return {
      bizOrgNo: '',
      isEdit: 'add',
      dialogVisible: false,
      dialogImageUrl: '',
      dialogVisible1: false,
      disabled: false,
      form: {},
      dialogForm: {
        maintenanceFile: '',
        maintenanceName: ''
      },
      isheight: 72,
      MeterPoints: { name: '', id: '' },
      props: {
        label: 'name',
        children: 'children',
        isLeaf: 'leaf'
      },
      iissize: 'medium',
      loading: false,
      tableData: [],
      total: 0,
      pageobj: {
        _pageNo: 0,
        _pageSize: 15
      },
      companyList: [],
      fileList: [],
      tableList2: []
    }
  },
  async created() {
    await this.getCompanyList()
    await this.getdatalist()
  },
  methods: {
    companyChange(val) {
      console.log(1)

      localStorage.setItem('companyId', val)
    },
    // 获取用电企业列表
    async getCompanyList() {
      const res = await getCompanyListApi({ companyId: this.bizOrgNo })
      console.log(res)
      this.companyList = res.data.list
      const companyId = +localStorage.getItem('companyId')
      if (companyId && this.companyList.find((i) => i.id == companyId)) {
        this.bizOrgNo = companyId
      } else {
        this.bizOrgNo = this.companyList[0].id
      }
    },
    // 初始化
    async getchushihua() {
      this.bizOrgNo = this.companyList[0].id
      localStorage.setItem('companyId', this.bizOrgNo)
    },
    // 获取数据
    async getdatalist() {
      this.loading = true
      const res = await getPageListApi({
        companyId: this.bizOrgNo,
        pageNo: this.pageobj._pageNo - 1,
        pageSize: this.pageobj._pageSize
      })
      console.log(res)
      this.tableData = res.data.list
      this.total = res.data.totalCount
      console.log(this.total)
      this.loading = false
    },
    async updateRecord(item) {
      console.log(item)
      this.$set(this.dialogForm, 'bh', item.bh)
      this.$set(this.dialogForm, 'className', item.className)
      this.$set(this.dialogForm, 'classId', item.classId)
      this.$set(this.dialogForm, 'maintenanceFile', '')
      this.$set(this.dialogForm, 'maintenanceName', '')
      this.$set(this.dialogForm, 'maintenanceYear', dayjs().format('YYYY'))
      this.$set(
        this.dialogForm,
        'maintenanceDate',
        dayjs().format('YYYY-MM-DD')
      )
      this.getMaintenanceList(item.classId)
      this.dialogVisible = true
      console.log(this.dialogForm)
    },
    download(val) {
      console.log(val)
    },
    onChange(file, fileList) {
      console.log(file)
      console.log(fileList)
      this.$set(this.dialogForm, 'maintenanceFile', file.raw)
      this.$set(this.dialogForm, 'maintenanceName', file.name)
      this.fileList = fileList
    },
    onRemove(file, fileList) {
      console.log(file)
      console.log(fileList)
      this.fileList = fileList
      this.$set(this.dialogForm, 'maintenanceFile', '')
      this.$set(this.dialogForm, 'maintenanceName', '')
    },
    async getMaintenanceList(id) {
      const res = await getMaintenanceListApi({ classId: id })
      this.tableList2 = res.data.list
    },
    async submit() {
      console.log(this.fileList)
      console.log(this.dialogForm)
      const res = await addMaintenanceApi(this.dialogForm)
      console.log(res)
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: '更新成功',
          duration: 2000
        })
        this.dialogVisible = false
        this.getdatalist()
      } else {
        this.$message({
          type: 'error',
          message: res.message,
          duration: 2000
        })
      }
    },
    // 刷新列表
    shuaxin() {
      this.getdatalist('')
      this.$message({
        type: 'success',
        message: '列表刷新成功',
        duration: 2000
      })
    },
    chaxun() {
      this.getdatalist()
    },
    downloadFile(fileName, base64Data) {
      const byteCharacters = atob(base64Data)
      const byteNumbers = new Array(byteCharacters.length)
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i)
      }
      const byteArray = new Uint8Array(byteNumbers)
      const blob = new Blob([byteArray], { type: 'application/octet-stream' })

      const url = URL.createObjectURL(blob)

      const a = document.createElement('a')
      a.style.display = 'none'
      a.href = url
      a.download = fileName

      document.body.appendChild(a)
      a.click()

      URL.revokeObjectURL(url)
      document.body.removeChild(a)
    },
    // 导出
    daochu() {
      exportexcel(
        '/ecm-microservice-biz/ecm/device/ledger/management/export',
        { companyId: this.bizOrgNo },
        '设备台账管理'
      )
    },
    command(val) {
      if (val === '默认') {
        this.iissize = 'medium'
      } else if (val === '中等') {
        this.iissize = 'small'
      } else {
        this.iissize = 'mini'
      }
    },
    diaClose() {
      this.dialogVisible = false
      this.dialogForm = {
        maintenanceFile: '',
        maintenanceName: ''
      }
      this.fileList = []
    },
    async chongzhi() {
      await this.getchushihua()
      this.getdatalist('')
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-upload-list {
  width: 90%;
}
::v-deep .upload-demo {
  display: flex;
}
.upload {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
}
.bigbox {
  display: flex;
  flex-direction: column;
  background-color: #f1f1f1;
  padding: 10px;
  height: 100%;
  .topbox {
    background-color: #fff;
    padding: 20px;
    box-sizing: border-box;
    height: 80px !important;
    width: 100% !important;
    // transition-property: all;
    // transition-duration: 0.2s;
  }
  .bodybox {
    flex: 1;
    background-color: #fff;
    margin-top: 10px;
    padding: 20px;
    .titlebox {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
      .text {
        font-weight: bold;
        font-size: 18px;
      }
      .right {
        align-items: center;
        i {
          margin-left: 10px;
        }
      }
    }
    .fenye {
      margin-top: 15px;
      text-align: right;
    }
  }
}
</style>
